﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using ArchiSimple.Windows.Model;
using System.Runtime.Serialization;
using System.IO;
using System.IO.Compression;

namespace ArchiSimple.Windows.Dao
{
    public class PlanDao
    {
        private Type[] types = new Type[]
        {
            typeof(Plan),
            typeof(Wall),
            typeof(Point),
            typeof(Room),
        };

        public Plan Load(string fileName)
        {
#if !NETFX_CORE
            using (var file = File.OpenRead(fileName))
            {
                using (var zipFile = new GZipStream(file, CompressionMode.Decompress))
                {
                    var serializer = GetSerializer();

                    return (Plan)serializer.ReadObject(zipFile);
                }
            }
#else
            return null;
#endif
        }

        private static DataContractSerializer GetSerializer()
        {
#if NETFX_CORE
            var serializer = new DataContractSerializer(typeof(Plan), new DataContractSerializerSettings
            {
                MaxItemsInObjectGraph = int.MaxValue,
                PreserveObjectReferences = true,
                DataContractResolver = new PlanContractResolver()
            });
#else
            var serializer = new DataContractSerializer(typeof(Plan), null, int.MaxValue, false, true, null, new PlanContractResolver());
#endif
            return serializer;
        }

        public void Save(string fileName, Plan plan)
        {
#if !NETFX_CORE
            using (var file = File.OpenWrite(fileName))
            {
                using (var zipFile = new GZipStream(file, CompressionMode.Compress, false))
                {
                    var serializer = GetSerializer();

                    serializer.WriteObject(zipFile, plan);
                }
            }
#endif
        }
    }
}
